package org.iubbo.proxy.common.utils;

import java.util.UUID;

/**
 * @Description 字符串工具类
 * @Author luyu
 **/
public class StringUtil {
    private StringUtil() {
    }

    public static String valueOf(Object obj) {
        return (obj == null) ? "" : obj.toString();
    }

    /**
     * 非空
     *
     * @param string
     * @return
     */
    public static boolean isNotEmpty(String string) {
        return (string != null && string.length() > 0);
    }

    /**
     * 检查指定的字符串是否为空。
     *
     * @param value 待检查的字符串
     * @return true/false
     */
    public static boolean isEmpty(String value) {
        if (value == null || value.length() == 0) {
            return true;
        }
        return false;
    }

    /**
     * uuid，无“-”，长度32
     *
     * @return
     */
    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        String id = uuid.toString();
        id = id.replaceAll("-", "");
        return id;
    }

    /**
     * 随机数字符串
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            double rd = Math.random() * 10;
            sb.append(String.valueOf(rd).substring(0, 1));
        }
        return sb.toString();
    }

    /**
     * 加法
     *
     * @param numberA
     * @param numberB
     * @return
     */
    public static String add(String numberA, String numberB) {
        if (null == numberA || null == numberB) {
            // 加数为空
            return null;
        }
        int lenA = numberA.length();
        int lenB = numberB.length();
        StringBuilder sbSum = new StringBuilder();
        String sLong = null;
        String sShort = null;
        if (lenA >= lenB) {
            sLong = numberA;
            sShort = numberB;
        } else {
            sLong = numberB;
            sShort = numberA;
        }
        int plus = 0;
        for (int i = 0; i < sShort.length(); i++) {
            int C = Integer.valueOf(sLong.substring(sLong.length() - 1 - i, sLong.length() - i));
            C += Integer.valueOf(sShort.substring(sShort.length() - 1 - i, sShort.length() - i));
            C += plus;
            if (C >= 10) {
                C = C - 10;
                plus = 1;
            } else {
                plus = 0;
            }
            sbSum.insert(0, C);
        }

        int j = sShort.length();
        while (j < sLong.length()) {
            int C = Integer.valueOf(sLong.substring(sLong.length() - j - 1, sLong.length() - j));
            C += plus;
            if (C >= 10) {
                C = C - 10;
                plus = 1;
            } else {
                plus = 0;
            }
            sbSum.insert(0, C);
            j++;
        }
        if (plus == 1) {
            sbSum.insert(0, 1);
        }

        return sbSum.toString();
    }
}
